#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import wsgiref.handlers

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
import os
from google.appengine.ext.webapp import template

## Imports for using Youtube API
import gdata.youtube
import gdata.youtube.service
import gdata.alt.appengine

## Global Variables
global blobtypes
blobtypes={"0":"General","1":"Image","2":"Link","3":"Video"}

## DataStore Classes
class Task(db.Model):
	title=db.StringProperty(multiline=False)
	taskid=db.IntegerProperty()	
	author=db.UserProperty()
	description=db.StringProperty(multiline=True)
	date=db.DateTimeProperty(auto_now_add=True)
	complete=db.BooleanProperty()
	deadline=db.DateTimeProperty(auto_now_add=False)	

class Blob(db.Model):
	blobid=db.IntegerProperty()
	task=db.ReferenceProperty(Task)
	title=db.StringProperty(multiline=False)
	author=db.UserProperty()
	contents=db.TextProperty()
	description=db.StringProperty(multiline=True)
	date=db.DateTimeProperty(auto_now_add=True)
	blobtype=db.IntegerProperty()
	short=db.BooleanProperty()

## Get last (limit) tasks in date descending order
def getTasks(limit=10):
	tasks=db.GqlQuery("SELECT * FROM Task ORDER BY date DESC LIMIT :lim",lim=limit)
	return tasks

## Create and update tasks
def setTask(title=False,author=False,description=False,complete=False):
	#test for existing task
	query=db.Query(Task)
	query=Blob.all()
	query.filter('title =',title)	
	tasks=query.fetch(limit=1)
	#task doesn't exist so create it
	if not tasks:
		task=Task()
		(task.title,task.author,task.description,task.complete)=(title,users.get_current_user(),description,task)
	#task exists so update it	
	else:
		#find existing task
		for task in tasks:
			#updates title if supplied as argument
			if title!=False:
				task.title=title
			#updates description if supplied as argument
			if description!=False:
				task.description=description
	task.put()	
	return

## Get the last (limit) blobs sorted by date
def getBlobs(limit=10):
	blobs=db.GqlQuery("SELECT * FROM Blob ORDER BY date DESC LIMIT 10")	
	return blobs

## Create and update blobs
def setBlob(title="",contents="",description="",blobtype=0,taskid=False,author=users.get_current_user()):
	shorten=False
	# generate description from contents if description not supplied	
	if description=="" and len(contents)>50:
		for i in range(0,50):
			description+=contents[i]
		shorten=True
	else:
		description=None
	# if a parent taskid is supplied get the parent task object
	if taskid:	
		parenttask=db.GqlQuery("SELECT * FROM Task WHERE taskid = :idno",idno=taskid)
		parenttask=parenttask.fetch(1)[0]
	else:
		parenttask=None
	
	#if title=="":
	#	if getBlobType(contents)==2:
	#		# in future implement url fetch to get title	
	#		title="URL"	

	# test for exisitng blob
	query=db.Query(Blob)
	query=Blob.all()
	
	# if title is blank search using content instead (slower)	
	if title!="":
		query.filter('title =',title)
	else:
		query.filter('contents =',contents)	
	blobs=query.fetch(limit=1)

	# blob doesn't exist so create it
	if query.count()==0:
		# get the last blob submitted
		lastblob=db.GqlQuery("SELECT * FROM Blob ORDER BY date DESC LIMIT 1")
		# if other blobs exist get last blobid and add 1 to it otherwise blobid is 0
		try:		
			blobid=lastblob[0].blobid+1
		except:
			blobid=0		
		blob=Blob()
		if parenttask!=None:
			(blob.title,blob.author,blob.contents,blob.description,blob.task,blob.blobtype,blob.blobid,blob.short)=(title,users.get_current_user(),contents,description,parenttask.key(),blobtype,blobid,shorten)
		else:
			(blob.title,blob.author,blob.contents,blob.description,blob.task,blob.blobtype,blob.blobid,blob.short)=(title,users.get_current_user(),contents,description,None,blobtype,blobid,shorten)	
	#blob exists so update it
	else:
		for blob in blobs:	
			#updates title if supplied as argument
			if title!=False:
				blob.title=title
			#updates description if supplied as argument
			if description!=False:
				blob.description=description
			#updates contents if supplied as argument
			if contents!=False:
				blob.contents=contents
			#updates taskid if supplied as argument
			if taskid!=False:
				blob.task=parenttask.key()
			# updates short:
			blob.short=shorten
	blob.put()
	return

## function to determine the blobtype given the contents of the blob
def getBlobType(contents):
	#implement detection later
	words=contents.split(" ")
	picExtensions=['jpg','png','jpeg','gif','psd']
	if len(words)==1:
		# check for url
		if words[0].find('http://') or words[0].find('www.'):
			# check if url is a picture
			extension=words[0].split('.')[-1]
			if extension in picExtensions:
				# url is a picture so blobtype is 1				
				return 1
			
			if words[0].find('youtube.com')>0:
				# url is a video so blobtype is 3
				return 3						
			else:
				# url is normal url so blobtype is 2
				return 2
	# otherwise blob is set as general type
	return 0	

## Page Handlers
class MainHandler(webapp.RequestHandler):
  def get(self):
	setBlob("test2","this is a 2nd test")
	blobs=getBlobs()	
	template_values= {
	'blobs':blobs	
	}
	path = os.path.join(os.path.dirname(__file__), 'index.html')
	self.response.out.write(template.render(path, template_values))

class viewBlobHandler(webapp.RequestHandler):
	def get(self):
		blobid=self.request.get('id')
		blobs=db.GqlQuery("SELECT * FROM Blob WHERE blobid = "+blobid)
		blob=blobs[0]		
		template_values= {
			'blob':blob		
		}
			
		path = os.path.join(os.path.dirname(__file__), 'viewblob.html')
		self.response.out.write(template.render(path, template_values))

class submitBlobHandler(webapp.RequestHandler):
	def post(self):
		blobtype=getBlobType(self.request.get('contents'))
		contents=self.request.get('contents')
		description=self.request.get('description')		
		setBlob(self.request.get('title'),contents,description,blobtype)
		self.redirect('/')
	def get(self):
		template_values= {
			'blobtypes':blobtypes		
		}
		
		path = os.path.join(os.path.dirname(__file__), 'submitblob.html')
		self.response.out.write(template.render(path, template_values))		
		    
def main():
  application = webapp.WSGIApplication([('/', MainHandler),('/viewblob',viewBlobHandler),('/submitblob',submitBlobHandler)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
